package cn.live.kyle.questionnaire.question;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import cn.live.kyle.questionnaire.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class QuestionMultiselect extends QuestionItem {

	private NodeList mOptionList;

	private ViewGroup mOptionGroup;
	private int mAnswer = 0;

	public QuestionMultiselect(Element element, QuestionPage page) {
		super(element, page);

		ViewGroup container = page.getQuestionViewContainer();
		Context context = container.getContext();
		mQuestionItemView = LayoutInflater.from(context).inflate(
				R.layout.question_multiselect, container, false);
		mOptionGroup = (ViewGroup) mQuestionItemView
				.findViewById(R.id.optionGroup);

		String answer = mElement.getAttribute(QuestionDomParser.ATTR_ANSWER);
		if (answer != null && answer.length() > 0) {
			mAnswer = Integer.valueOf(answer);
			mIsAnswered = true;
		}

		mOptionList = mElement
				.getElementsByTagName(QuestionDomParser.TAG_OPTION);
		int optionCount = mOptionList.getLength();
		for (int i = 0; i < optionCount; i++) {
			CheckBox button = (CheckBox) (LayoutInflater.from(context).inflate(
					R.layout.question_multiselect_option, mOptionGroup, false));
			mOptionGroup.addView(button);
			Element option = (Element) mOptionList.item(i);
			String title = option.getAttribute(QuestionDomParser.ATTR_TITLE);
			button.setText(title);

			if (getOptionStateFromAnswer(mAnswer, i)) {
				button.setChecked(true);
			}

			button.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton button,
						boolean checked) {
					int index = mOptionGroup.indexOfChild(button);
					if (checked) {
						mAnswer = setOptionStateToAnswer(mAnswer, index);
					} else {
						mAnswer = clearOptionStateToAnswer(mAnswer, index);
					}

					mElement.setAttribute(QuestionDomParser.ATTR_ANSWER,
							String.valueOf(mAnswer));
					mIsAnswered = true;
					mQuestionPage.onQuestionItemStateChanged();
				}
			});
		}
	}

	public static boolean getOptionStateFromAnswer(int answer, int index) {
		return (answer & (1 << index)) > 0;
	}

	public static int setOptionStateToAnswer(int answer, int index) {
		return answer | (1 << index);
	}

	public static int clearOptionStateToAnswer(int answer, int index) {
		return answer & (~(1 << index));
	}

}